package com.hekang.fragmentdemo;

import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class ManageFragmentActivity extends AppCompatActivity {
    private FragmentManager fragmentManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_manage_fragment);
    }


    /**
     * 添加Fragment
     */
    public void add(View view) {
        //打开事物
        if (fragmentManager == null || fragmentManager.findFragmentByTag("fragment") == null) {
            fragmentManager = getSupportFragmentManager();
            FragmentTransaction transaction = fragmentManager.beginTransaction();
            FragmentTest fragmentTest = new FragmentTest();
            transaction.add(R.id.fl_container, fragmentTest, "fragment");
            transaction.commit();
        }
    }

    /**
     * 删除Fragment
     */
    public void remove(View view) {
        if (fragmentManager != null && fragmentManager.findFragmentByTag("fragment") != null) {
            FragmentTransaction transaction = fragmentManager.beginTransaction();
            transaction.remove(fragmentManager.findFragmentByTag("fragment"));
            transaction.commit();
        } else {
            Toast.makeText(this, "暂无可删除", Toast.LENGTH_SHORT).show();
        }
    }


    /**
     * 替换Fragment
     */
    public void replace(View view){
        if (fragmentManager != null && fragmentManager.findFragmentByTag("fragment") != null) {
            FragmentTransaction transaction = fragmentManager.beginTransaction();
            AnotherFragmentTest anotherFragmentTest = new AnotherFragmentTest();
            transaction.replace(R.id.fl_container,anotherFragmentTest);
            transaction.commit();
        } else {
            Toast.makeText(this, "暂无可替换", Toast.LENGTH_SHORT).show();
        }
    }


    /**
     * 隐藏Fragment
     * @param view
     */
    public void hide(View view){
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.hide(fragmentManager.findFragmentByTag("fragment"));
    }

    /**
     * 显示Fragment
     * @param view
     */
    public void show(View view){
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.show(fragmentManager.findFragmentByTag("fragment"));
    }
}
